package com.cyj.calls;

import com.cyj.calls.model.Orders;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class JobTest {

    public static void main(String[] args) {
        // 初始化数据
        List<List<Integer>> groupList = new ArrayList<>();
        for (int j = 0; j < 1000; j++) {
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < 2000; i++) {
                //生产随机数
                list.add(ThreadLocalRandom.current().nextInt(9999));
            }
            groupList.add(list);
        }
        // 创建计算线程池
        LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(3000);
        ThreadPoolExecutor calcThreadPool = new ThreadPoolExecutor(100, 200, 1, TimeUnit.MINUTES, queue);
        // 创建同步计数器（协调多个线程）
        CountDownLatch countDownLatch = new CountDownLatch(groupList.size());
        // 开始并发计算
        List<Future<Orders>> futures = new ArrayList<>();
        for (List<Integer> list : groupList) {
            MyJobCallable callable = new MyJobCallable(list, countDownLatch);
            // 并发计算（开启多线程计算，不影响主线程执行）
            Future<Orders> future = calcThreadPool.submit(callable);
            futures.add(future);
        }
        System.out.println(futures.size());
        try {
            // 等待多线程结束
            countDownLatch.await();
            // 输出结果
            int c = 0;
            for (Future<Orders> future : futures) {
                if (future.isDone()) {
                    Orders orders = future.get();
                    System.out.println(orders.toString());
                    if (orders.getProductName() != null) {
                        c++;
                    }
                } else {
                    future.cancel(true);
                }
            }
            System.out.println(c);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
